package com.tjetc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tjetc.constant.CodeConstant;
import com.tjetc.constant.RedisConstant;
import com.tjetc.domain.*;
import com.tjetc.domain.District;
import com.tjetc.domain.HDepartment;
import com.tjetc.domain.HospitalLevel;
import com.tjetc.mapper.*;
import com.tjetc.util.DateUtil;
import com.tjetc.util.Db;
import com.tjetc.vo.HosWithPointDepartmentVo;
import com.tjetc.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.tjetc.service.HospitalService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Resource
    private HospitalMapper hospitalMapper;

    @Autowired
    private HospitalLevelMapper hospitalLevelMapper;

    @Autowired
    private HDepartmentMapper hDepartmentMapper;
    @Autowired
    private ClinicMapper clinicMapper;
    @Autowired
    private SchedulingMapper schedulingMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return hospitalMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Hospital record) {
        return hospitalMapper.insert(record);
    }

    @Override
    public int insertSelective(Hospital record) {
        return hospitalMapper.insertSelective(record);
    }

    @Override
    public Hospital selectByPrimaryKey(Integer id) {
        return hospitalMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Hospital record) {
        return hospitalMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Hospital record) {
        return hospitalMapper.updateByPrimaryKey(record);
    }

    @Override
    public Result selectByIdWithDepartments(Integer id) {
        Hospital hospital = hospitalMapper.selectByIdWithDepartments(id);
        return Result.ok(hospital);
    }

    @Override
    public Result selHosByPage(Integer curPage) {
        //分页查出对应的医院list
        PageHelper.startPage(curPage, 5);
        List<Hospital> list = hospitalMapper.selectAll();
        PageInfo<Hospital> pageInfo = new PageInfo<>(list);
        if (pageInfo.getList().size() == 0) {
            return new Result().setCode(CodeConstant.NO_MORE_HOSPITALS);
        }
        //循环封装成hosWithPointDepartmentVos的list
        List<HosWithPointDepartmentVo> hosWithPointDepartmentVos = new ArrayList<>();
        for (Hospital hospital : pageInfo.getList()) {
            HosWithPointDepartmentVo hosWithPointDepartmentVo = new HosWithPointDepartmentVo();
            hosWithPointDepartmentVo.setId(hospital.getId());
            hosWithPointDepartmentVo.setName(hospital.getName());
            hosWithPointDepartmentVo.setIcon(hospital.getIcon());
            HospitalLevel hospitalLevel = hospitalLevelMapper.selectByPrimaryKey(hospital.getTypeId());
            hosWithPointDepartmentVo.setType(hospitalLevel.getName());
            hosWithPointDepartmentVo.setIsAlternate(hospital.getIsAlternate());
            String address = hospital.getAddress();
            hosWithPointDepartmentVo.setDistrict(address.substring(address.indexOf("市") + 1, address.indexOf("区") + 1));
            List<HDepartment> hDepartments = hDepartmentMapper.selectPointByHid(hospital.getId());
            StringBuilder sb = new StringBuilder();
            for (HDepartment hDepartment : hDepartments) {
                sb.append(hDepartment.getName()).append(",");
            }
            if (!sb.isEmpty()) {
                sb.deleteCharAt(sb.length() - 1);
            }
            hosWithPointDepartmentVo.setPointDepartments(sb.toString());
            hosWithPointDepartmentVos.add(hosWithPointDepartmentVo);
        }

        return Result.ok(hosWithPointDepartmentVos);
    }

    @Override
    public List<Hospital> listHospital(String name, String address) {
        return hospitalMapper.listHospital(name, address);
    }

    @Override
    public Result findByName(String name) {
        List<Hospital> list = hospitalMapper.findByName(name);
        return Result.ok(list);
    }

    @Override
    public Result findByHosDep(String hosInput, String depInput) {
        if (!depInput.isEmpty()) {
            String s = "门诊急诊";
            if (s.contains(depInput)) {
                depInput = "-";
            }
        }
        if (!hosInput.isEmpty() && depInput.isEmpty()) {
            List<Hospital> list = hospitalMapper.findByHos(hosInput);
            return Result.ok(list);
        } else if (hosInput.isEmpty() && !depInput.isEmpty()) {
            List<Hospital> list = hospitalMapper.findByDep(depInput);
            return Result.ok(list);
        } else {
            List<Hospital> list = hospitalMapper.findByHosDep(hosInput, depInput);
            return Result.ok(list);
        }
    }

    @Override
    public Result getCountHos() {
        int count = hospitalMapper.getCountHos();
        return Result.ok(count);
    }

    @Override
    public Result getAllDistrict() {
        List<District> list = hospitalMapper.getAllDistrict();
        return Result.ok(list);
    }

    @Override
    public Result getHosByDis(String district, String level) {
        List<Hospital> list = hospitalMapper.getHosByDis(district, level);
        System.out.println(list);
        if (list.size() == 0) {
            return new Result().setCode(CodeConstant.NO_MORE_HOSPITALS);
        }
        //循环封装成hosWithPointDepartmentVos的list
        List<HosWithPointDepartmentVo> hosWithPointDepartmentVos = new ArrayList<>();
        for (Hospital hospital : list) {
            HosWithPointDepartmentVo hosWithPointDepartmentVo = new HosWithPointDepartmentVo();
            hosWithPointDepartmentVo.setId(hospital.getId());
            hosWithPointDepartmentVo.setName(hospital.getName());
            hosWithPointDepartmentVo.setIcon(hospital.getIcon());
            HospitalLevel hospitalLevel = hospitalLevelMapper.selectByPrimaryKey(hospital.getTypeId());
            hosWithPointDepartmentVo.setType(hospitalLevel.getName());
            hosWithPointDepartmentVo.setIsAlternate(hospital.getIsAlternate());
            String address = hospital.getAddress();
            hosWithPointDepartmentVo.setDistrict(address.substring(address.indexOf("市") + 1, address.indexOf("区") + 1));
            List<HDepartment> hDepartments = hDepartmentMapper.selectPointByHid(hospital.getId());
            StringBuilder sb = new StringBuilder();
            for (HDepartment hDepartment : hDepartments) {
                sb.append(hDepartment.getName()).append(",");
            }
            if (!sb.isEmpty()) {
                sb.deleteCharAt(sb.length() - 1);
            }
            hosWithPointDepartmentVo.setPointDepartments(sb.toString());
            hosWithPointDepartmentVos.add(hosWithPointDepartmentVo);
        }
        return Result.ok(hosWithPointDepartmentVos);
    }

    @Override
    public Result selByPage(Integer curPage, Integer pageSize, String name) {
        PageHelper.startPage(curPage, pageSize);
        List<Hospital> hospitals = hospitalMapper.findByName(name);
        PageInfo<Hospital> hospitalPageInfo = new PageInfo<>(hospitals);
        return Result.ok(hospitalPageInfo);
    }

    @Override
    @Transactional
    public Result update(Hospital hospital) {
        Hospital oldHospital = hospitalMapper.selectByPrimaryKey(hospital.getId());
        if (oldHospital == null) {
            return Result.fail("该医院不存在");
        }
        if (oldHospital.getIsAlternate() != hospital.getIsAlternate()){
            List<Clinic> clinics = clinicMapper.selByHosId(hospital.getId());
            for (Clinic clinic : clinics) {
                List<Scheduling> schedulings = schedulingMapper.selectByCid(clinic.getId());
                for (Scheduling scheduling : schedulings) {
                    scheduling.setIsAlternate(hospital.getIsAlternate());
                    schedulingMapper.updateByPrimaryKey(scheduling);
                    Db.jedis.del(RedisConstant.SCHEDULING_STATE + scheduling.getCid() + "-" + DateUtil.getDate(new Date()));
                }
            }
        }
        int rows = hospitalMapper.updateByPrimaryKey(hospital);
        return rows == 1 ? Result.ok() : Result.fail("更新失败");
    }

    @Override
    public Result delete(Integer id) {
        Hospital hospital = hospitalMapper.selectByPrimaryKey(id);
        if (hospital == null) {
            return Result.fail("该医院不存在");
        }
        List<HDepartment> hDepartments = hDepartmentMapper.selectByHid(id);
        if (hDepartments != null && !hDepartments.isEmpty()) {
            return Result.fail("该医院还绑定着下辖的科室和门诊");
        }
        int rows = hospitalMapper.deleteByPrimaryKey(id);
        return rows == 1 ? Result.ok() : Result.fail("删除失败");
    }

    @Override
    @Transactional
    public Result forceDel(Integer id) {
        int row = clinicMapper.deleteByHid(id);
        int row1 = hDepartmentMapper.deleteByHid(id);
        int row2 = hospitalMapper.deleteByPrimaryKey(id);
        return row2 == 1 ? Result.ok() : Result.fail("强制删除失败");
    }

    @Override
    public Result add(Hospital hospital) {
        int rows = hospitalMapper.insert(hospital);
        return rows == 1 ? Result.ok() : Result.fail("添加失败");
    }

    @Override
    public Result selAllhospital() {
        return Result.ok(hospitalMapper.selectAll());
    }

    @Override
    public Result selAll(Integer sgId, String location, Integer pageSize) {
        List<Hospital> list = hospitalMapper.allHospital(sgId, location, pageSize);
        Iterator<Hospital> iterator = list.iterator();
        while (iterator.hasNext()) {
            Hospital hospital = iterator.next();
            List<Clinic> clinics = hospital.getClinics();
            clinics.removeIf(clinic -> !clinic.getSgId().equals(sgId));
            if (clinics.size() == 0) {
                iterator.remove();
            }
        }
        return list.size() == 0 ? Result.fail() : Result.ok(list);
    }

    @Override
    public PageInfo<Hospital> getAllByName(Integer curPage, Integer pageSize, String name) {
        PageHelper.startPage(curPage, pageSize);
        List<Hospital> list = hospitalMapper.getAllByName(name);
        return new PageInfo<>(list);
    }

    @Override
    public Result addHos(Hospital hospital) {
        if (hospital.getId() == null) {
            int typeId = hospitalLevelMapper.selectByName(hospital.getLevel().getName());
            hospital.setTypeId(typeId);
            int rows = hospitalMapper.insert(hospital);
            if (rows > 0) {
                return Result.ok(rows);
            } else {
                return Result.fail("添加失败");
            }
        } else {
            int row = hospitalMapper.updateByPrimaryKey(hospital);
            if (row > 0) {
                return Result.ok(row);
            } else {
                return Result.fail("更新失败");
            }
        }
    }

    @Override
    public Result deleteById(Integer id) {
        int rows = hospitalMapper.deleteByPrimaryKey(id);
        return Result.ok(rows);
    }

    @Override
    public Result updateHos(Integer id, String desc, String guidance, String prompt) {
        Integer rows = hospitalMapper.updateHos(id, desc, guidance, prompt);
        if (rows > 0) {
            return Result.ok(selectByPrimaryKey(id));
        }
        return Result.fail();
    }
}
